<template>
	<view class="my-page">
		<!-- 头部信息区域 -->
		<view class="header">
			<image class="avatar" :src="userInfo.avatar"></image>
			<view class="user-info">
				<view class="user-info-wrap">
					<view class="username">{{ userInfo.nickname }}</view>
					<view style="display: flex" v-if="true">
						<button class="apply-btn" v-if="!isExpert" @click="showApplyExpertDialog = true">
							申请专家
						</button>
						<button class="apply-btn" v-if="!isTuiguang" @click="showApplyPromoterDialog = true">
							申请推广者
						</button>
					</view>
				</view>
				<view class="tag">
					<text v-for="(item, index) in userInfo.groupName" :key="index">{{
            item
          }}</text>
				</view>
				<view class="expert-desc">{{ userInfo.mark||'暂无备注' }}</view>
			</view>
		</view>

		<!-- 申请专家弹窗 -->
		<view class="custom-dialog" v-if="showApplyExpertDialog">
			<view class="dialog-mask" @tap="closeDialog"></view>
			<view class="dialog-content">
				<image class="dialog-img" src="https://www.rebirthealth.com/static/images/zhuanjia.jpg"></image>
				<view class="dialog-tip">支付{{(bizConfig.pledgeAmountExpert||0)/100}}元申请成为专家用户</view>
				<view class="agreement">
					<checkbox-group @change="onExpertAgreeChange">
						<label class="agreement-label">
							<checkbox value="agree" :checked="isAgreeExpert" color="#2F7FB9" />
							<text class="agreement-text">我已阅读并同意</text>
							<text class="agreement-link"
								@click.stop="navigateTo('/pages/my/settings/protocol')">《用户协议》</text>
							<text class="agreement-link"
								@click.stop="navigateTo('/pages/my/settings/protocol')">和《隐私政策》</text>
						</label>
					</checkbox-group>
				</view>
				<button class="confirm-btn" :disabled="!isAgreeExpert"
					@click="handleExpertApply((bizConfig.pledgeAmountExpert||0)/100)">去支付</button>
			</view>
		</view>

		<!-- 申请推广者弹窗 -->
		<view class="custom-dialog" v-if="showApplyPromoterDialog">
			<view class="dialog-mask" @tap="closeDialog"></view>
			<view class="dialog-content">
				<image class="dialog-img" src="https://www.rebirthealth.com/static/images/tuiguang.jpg"></image>
				<view class="dialog-tip">支付{{(bizConfig.pledgeAmountSpreader||0)/100}}元申请成为推广者用户</view>
				<view class="agreement">
					<checkbox-group @change="onExpertAgreeChange">
						<label class="agreement-label">
							<checkbox value="agree" :checked="isAgreeExpert" color="#2F7FB9" />
							<text class="agreement-text">我已阅读并同意</text>
							<text class="agreement-link"
								@click.stop="navigateTo('/pages/my/settings/protocol')">《用户协议》</text>
							<text class="agreement-link"
								@click.stop="navigateTo('/pages/my/settings/protocol')">和《隐私政策》</text>
						</label>
					</checkbox-group>
				</view>
				<button class="confirm-btn" :disabled="!isAgreeExpert"
					@click="handleExpertApply((bizConfig.pledgeAmountSpreader||0)/100)">去支付</button>
			</view>
		</view>

		<view class="body-view">
			<!-- 金额统计区域 只有当用户是推广者|专家的时候才显示这个模块-->
			<view class="amount-box" v-if="isExpert||isTuiguang">
				<view class="amount-item" v-for="(item, index) in userInfo.brokerages" :key="index"
					@click="navigateTo('/pages/my/account')">
					<view class="amount">{{ item.lang == "zh" ? "¥" : "$"
            }}{{ (item.brokeragePrice || 0) / 100 }}</view>
					<view class="amount-label">可提金额</view>
				</view>
			</view>

			<!-- 快捷入口区域 -->
			<!-- <view class="shortcut-box" v-if="!isPutong">
        <view
          class="shortcut-item"
          v-for="(item, index) in shortcutList"
          :key="index"
          @click="handleShortcutClick(item)"
        >
          <image class="shortcut-icon" :src="item.icon"></image>
          <view class="shortcut-label">{{ item.label }}</view>
        </view>
      </view> -->

			<!-- 功能列表区域 -->
			<view class="func-list">
				<view class="func-item" v-for="(item, index) in funTempList" :key="index"
					@click="handleFuncClick(item)">
					<image class="func-icon" :src="item.icon"></image>
					<view class="func-label" v-if="item.label!=='在线客服'">{{ item.label }}</view>
					<button class="func-button" v-else open-type="contact">{{ item.label }}</button>
					<image class="arrow-icon" src="https://www.rebirthealth.com/static/images/arrow-right.png"></image>
				</view>
			</view>

		</view>
	</view>
</template>

<script>
	import {
		getUserInfo,
		getBizConfig,
		applyReceiverUser,
		applySpreaderUser,
		prepay
	} from "@/api";
	export default {
		data() {
			return {
				userInfo: {},
				bizConfig: {},
				// 弹窗控制变量
				showApplyExpertDialog: false,
				showApplyPromoterDialog: false,
				// 协议勾选状态
				isAgreeExpert: false,
				// 快捷入口数据
				shortcutList: [{
						icon: "https://www.rebirthealth.com/static/images/order-received.png",
						label: "已接单",
						type: "orderReceived",
					},
					{
						icon: "https://www.rebirthealth.com/static/images/bounty.png",
						label: "悬赏中",
						type: "bounty",
					},
					{
						icon: "https://www.rebirthealth.com/static/images/order-accepted.png",
						label: "已接单",
						type: "orderAccepted",
					},
				],
				// 功能列表数据
				funcList: [{
						icon: "https://www.rebirthealth.com/static/images/personal-info.png",
						label: "个人资料",
						type: "personalInfo",
					},
					{
						icon: "https://www.rebirthealth.com/static/images/my-orders.png",
						label: "我的发单",
						type: "myOrders",
					},
					{
						icon: "https://www.rebirthealth.com/static/images/my-received-orders.png",
						label: "我的接单",
						type: "myReceivedOrders",
					},
					{
						icon: "https://www.rebirthealth.com/static/images/online-service.png",
						label: "在线客服",
						type: "onlineService",
					},
					{
						icon: "https://www.rebirthealth.com/static/images/settings.png",
						label: "设置",
						type: "settings",
					},
				],
			};
		},
		async onLoad() {
			//获取业务参数
			let res = await getBizConfig();
			this.bizConfig = res;
		},
		onShow() {
			this.getUserInfo();
		},
		computed: {
			isExpert() {
				let userInfo = this.userInfo;
				if (userInfo && userInfo.groupIds) {
					let groupIds = userInfo.groupIds;
					// 如果包含1-普通用户
					// 如果包含2-推广者
					// 如果包含3-专家
					if (groupIds.includes(3)) {
						return true;
					}
				}
				return false;
			},
			isPutong() {
				let userInfo = this.userInfo;
				if (userInfo && userInfo.groupIds) {
					let groupIds = userInfo.groupIds;
					// 如果包含1-普通用户
					// 如果包含2-推广者
					// 如果包含3-专家
					if (groupIds.includes(1)) {
						return true;
					}
				}
				return false;
			},
			isTuiguang() {
				let userInfo = this.userInfo;
				if (userInfo && userInfo.groupIds) {
					let groupIds = userInfo.groupIds;
					// 如果包含1-普通用户
					// 如果包含2-推广者
					// 如果包含3-专家
					if (groupIds.includes(2)) {
						return true;
					}
				}
				return false;
			},
			funTempList() {
				if (!this.isExpert) {
					return this.funcList.filter((c) => c.label !== "我的接单");
				} else {
					return this.funcList;
				}
			},
		},
		methods: {
			async getUserInfo() {
				let res = await getUserInfo();
				if (res) {
					uni.setStorageSync("userInfo", res);
					this.userInfo = res;
				}
			},
			// 快捷入口点击事件
			handleShortcutClick(item) {
				uni.showToast({
					title: `点击了${item.label}，功能待实现`,
					icon: "none"
				});
				// 可根据 item.type 做不同逻辑，比如跳转对应页面
			},
			// 功能列表点击事件
			handleFuncClick(item) {
				if (item.label === "我的发单") {
					uni.navigateTo({
						url: "/pages/my/myOrders?type=1",
					});
				} else if (item.label === "我的接单") {
					uni.navigateTo({
						url: "/pages/my/myOrders?type=2",
					});
				} else if (item.label === "个人资料") {
					uni.navigateTo({
						url: "/pages/my/personalInfo",
					});
				} else if (item.label === "设置") {
					uni.navigateTo({
						url: "/pages/my/settings",
					});
				} else if (item.label === "在线客服") {
					// 从业务配置中获取客服企业的 CorpId（需提前在 bizConfig 中配置）
					const serviceCorpId = ''; // 请替换为实际的 CorpId
					wx.openCustomerServiceChat({
						corpId: serviceCorpId, // 企业微信的 CorpId
						// 可选参数：会话初始消息（示例）
						// greeting: '您好，请问有什么可以帮您的？',
						// success: (res) => {
						//   console.log('客服会话打开成功', res);
						// },
						// fail: (err) => {
						//   console.error('客服会话打开失败', err);
						// }
					});
				} else {
					uni.showToast({
						title: `点击了${item.label}，功能待实现`,
						icon: "none",
					});
				}
				// 可根据 item.type 做不同逻辑，比如跳转对应页面
			},
			navigateTo(path) {
				if (path) {
					uni.navigateTo({
						url: path
					});
				}
			},
			// 处理专家申请支付
			async handleExpertApply(amount) {
				if (!this.isAgreeExpert) return;

				try {
					let orderId = undefined;
					// 调用后端接口
					if (this.showApplyExpertDialog) {
						orderId = await applyReceiverUser();
					} else {
						orderId = await applySpreaderUser();
					}

					// 调起微信支付
					const payConfig = await prepay(orderId);
					if (!payConfig) {
						uni.showToast({
							title: '支付订单创建失败',
							icon: 'none',
							duration: 2000
						});
						return;
					}

					// 执行微信支付
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: payConfig.timeStamp,
						nonceStr: payConfig.nonceStr,
						package: payConfig.packageValue,
						signType: payConfig.signType,
						paySign: payConfig.paySign,
						success: (res) => {
							console.log('支付成功，响应：', res); // 添加日志确认是否执行
							//这里需要延时五秒，因为微信支付成功后，订单状态需要五秒才能同步到后端
							setTimeout(() => {
								// 支付成功：刷新数据，关闭弹窗，显示提示
								this.closeDialog();
								this.getUserInfo();
								uni.showToast({
									title: '支付成功',
									icon: 'success',
									duration: 1500
								});
							}, 5000);
						},
						fail: (err) => {
							// 支付失败/取消：显示提示，不刷新数据
							const errMsg = err.errMsg || '支付失败';
							if (errMsg.includes('cancel')) {
								uni.showToast({
									title: '支付已取消',
									icon: 'none',
									duration: 1500
								});
							} else {
								uni.showToast({
									title: `支付失败：${errMsg}`,
									icon: 'none',
									duration: 2000
								});
							}
						},
					});
				} catch (error) {
					console.error('支付异常:', error);
					uni.showToast({
						title: '网络异常，请稍后重试',
						icon: 'none',
						duration: 2000
					});
				}
			},
			// 专家协议勾选状态变化
			onExpertAgreeChange(e) {
				this.isAgreeExpert = e.detail.value.includes('agree');
			},
			// 关闭弹窗
			closeDialog() {
				this.showApplyExpertDialog = false;
				this.showApplyPromoterDialog = false;
				// 重置勾选状态
				this.isAgreeExpert = false;
			},
		},
	};
</script>
<style lang="less" scoped>
	.my-page {
		background-color: rgba(243, 244, 246, 1);
		min-height: 100vh;

		// 头部区域样式
		.header {
			display: flex;
			padding: 32rpx;
			padding-top: 218rpx;
			color: #fff;
			height: 478rpx;
			background: linear-gradient(90deg, #2f7fb9 0%, #045fb2 100%);

			.avatar {
				border: 1px solid #fff;
				width: 96rpx;
				height: 96rpx;
				border-radius: 50%;
				margin-right: 32rpx;
				margin-top: 6rpx;
			}

			.user-info {
				display: flex;
				flex-direction: column;
				justify-content: start;
				width: 557rpx;

				&-wrap {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 16rpx;
				}

				.tag {
					margin-bottom: 30rpx;

					text {
						padding: 0 10rpx;
						background: #339694;
						color: #fff;
						margin-right: 10rpx;
					}
				}

				.username {
					font-size: 48rpx;
					font-weight: bold;
				}

				.expert-desc {
					font-size: 28rpx;
					line-height: 36rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
				}

				.apply-btn {
					margin-top: 10rpx;
					background-color: transparent;
					color: #fff;
					font-size: 20rpx;
					line-height: 56rpx;
					padding: 8rpx 16rpx;
					border-radius: 40rpx;
					border: 2rpx solid rgba(212, 234, 255, 0.45);

					&:nth-child(1) {
						margin-right: 16rpx;
					}
				}
			}
		}

		.body-view {
			margin-top: -242rpx;
		}

		// 金额统计区域样式
		.amount-box {
			display: flex;
			justify-content: space-between;
			padding: 0 32rpx;
			margin-bottom: 16rpx;

			.amount-item {
				width: 326rpx;
				height: 124rpx;
				background-color: #fff;
				border-radius: 16rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;

				.amount {
					font-size: 36rpx;
					font-weight: bold;
					color: #f85c02;
					margin-bottom: 7rpx;
				}

				.amount-label {
					font-size: 28rpx;
					color: #333333;
				}
			}
		}

		// 快捷入口区域样式
		.shortcut-box {
			display: flex;
			padding: 32rpx 68rpx;
			background-color: #fff;
			margin: 0 32rpx;
			border-radius: 16rpx;
			justify-content: space-between;
			margin-bottom: 50rpx;

			.shortcut-item {
				text-align: center;

				.shortcut-icon {
					width: 96rpx;
					height: 96rpx;
					margin-bottom: 16rpx;
				}

				.shortcut-label {
					font-size: 28rpx;
					color: #333333;
				}
			}
		}

		// 功能列表区域样式
		.func-list {
			margin: 0 32rpx;
			padding-bottom: 32rpx;

			.func-item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 34rpx 32rpx;
				height: 120rpx;
				margin-bottom: 16rpx;
				background-color: #fff;
				border-radius: 16rpx;
				box-sizing: border-box;

				.func-icon {
					width: 52rpx;
					height: 52rpx;
					margin-right: 32rpx;
				}

				.func-label {
					font-size: 30rpx;
					color: #333333;
					flex: 1;
				}

				.func-button {
					font-size: 30rpx;
					color: #333333;
					flex: 1;
					text-align: left;
					padding: 0;
					background-color: #FFF;

					&::after {
						border: none;
					}
				}

				.arrow-icon {
					width: 16rpx;
					height: 24rpx;
				}
			}
		}

		// 自定义弹窗样式
		.custom-dialog {
			.dialog-mask {
				position: fixed;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				background: rgba(0, 0, 0, 0.5);
				z-index: 999;
			}

			.dialog-content {
				position: fixed;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
				width: 600rpx;
				background: #fff;
				border-radius: 16rpx;
				padding: 40rpx;
				z-index: 1000;

				/* 添加以下代码实现弹窗高度占满屏幕80%并添加滚动条 */
				height: 80vh;
				/* 设置高度为视口高度的80% */
				max-height: 80vh;
				overflow-y: auto;
				/* 添加垂直滚动条 */

				.dialog-img {
					width: 100%;
					height: 2568rpx;
					border-radius: 8rpx;
					margin-bottom: 30rpx;
				}

				.dialog-tip {
					font-size: 32rpx;
					color: #333;
					text-align: center;
					margin-bottom: 40rpx;
					font-weight: bold;
				}

				.agreement {
					margin-bottom: 40rpx;

					.agreement-label {
						display: flex;
						align-items: center;
						font-size: 24rpx;
						color: #666;

						.agreement-text {
							margin: 0 8rpx;
						}

						.agreement-link {
							color: #2F7FB9;
							text-decoration: underline;
						}
					}
				}

				.confirm-btn {
					width: 100%;
					height: 80rpx;
					line-height: 80rpx;
					background: linear-gradient(90deg, #2F7FB9 0%, #045FB2 100%);
					color: #fff;
					font-size: 32rpx;
					border-radius: 8rpx;
					border: none;

					&[disabled] {
						background: #ccc;
						color: #999;
					}
				}
			}
		}
	}
</style>